package org.varscape.core.reader;

import java.io.IOException;

import org.broad.tribble.readers.TabixReader;
import org.broad.tribble.readers.TabixReader.Iterator;
import org.varscape.core.util.Tokenizer;


//For Tabix files. Currently we use Tribble to help us.
public class VCFIndexedReader extends AbstractVCFReader implements IIndexedReader{
	
	private TabixReader tr;
	private String filePath;
	
	public VCFIndexedReader(String path) {
		filePath = path;
		tr = null;
	}

	// Can currently only return one line.
	// By VCF definition, there can be more than one lines for position.
	// i.e. there may be >1 lines with the same chromosome number and position.  
	private String getLine(String chr, int pos) {
		if (tr == null) {
			try {
				tr = new TabixReader(filePath);
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		}
		String returnStr = null;
		Iterator it = tr.query(chr+":"+pos+"-"+pos);
		
		try {
			returnStr = it.next();
		} catch (IOException e) {
			e.printStackTrace();
		}
//		if (returnStr != null) {
//			returnStr = returnStr.substring(0, returnStr.length()-1); // -1 to get rid of the UNIX line break 
//		}
		return returnStr;
	}
	
	// Implementation for moveTo in IIndexedReader
	@Override
	public boolean moveTo(String chr, int pos) {
		String line = getLine(chr, pos);
		if (line == null) {
			return false;
		} else {
			currentLine = line;
			currentLineTokens = Tokenizer.tabTokenize(currentLine);
			return true;
		}
	}

	@Override
	public void close() {
		if (tr != null) {
			tr.close();
		}
	}

	// Haven't tested this
	@Override
	public String[] getHeaders() {
		return VariationFileReaderFactory.buildIteratorReader(filePath).getHeaders();
	}

	public static void main(String[] args) {
		VCFIndexedReader reader = new VCFIndexedReader(System.getProperty("user.dir") + "/data/example/example.vcf.gz");
		reader.moveTo("1", 16850);
		System.out.println(reader.currentLine);
		System.out.println(reader.getHeaders()[1]);
		System.out.println(reader.readRef());
		System.out.println(reader.readAlt());
	}
}
